const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog,
} = require("../controller/blog");

const { SuccessModel, ErrorModel } = require("../model/res");

const logincheck = (req) => {
  console.error("i checked login", req.session);
  if (!req.session.username) {
    return Promise.resolve(new ErrorModel("fail"));
  }
};

const handleBlogRouter = (req, res) => {
  const method = req.method;

  if (method === "GET" && req.path === "/api/blog/list") {
    const { author, keyword } = req.query;
    // const listData = getList(author, keyword);
    // console.log(listData);
    // return new SuccessModel(listData);
    const result = getList(author, keyword);
    return result
      .then((listData) => {
        return new SuccessModel(listData);
      })
      .catch((err) => {
        return new ErrorModel(err);
      });
  }
  if (method === "GET" && req.path === "/api/blog/detail") {
    const id = req.query.id;
    return getDetail(id).then((data) => new SuccessModel(data));
  }
  if (method === "POST" && req.path === "/api/blog/new") {
    const blogData = req.body;
    // const logincheckres = logincheck(req);
    // if (logincheckres) {
    //   console.log("over here?");
    //   return logincheckres;
    // }

    // blogData.author = req.session.username;

    return newBlog(blogData).then((data) => new SuccessModel(data));
  }
  if (method === "POST" && req.path === "/api/blog/update") {
    const logincheck = logincheck(req);
    if (logincheck) {
      return logincheck;
    }

    return updateBlog(req.query.id, req.body).then((res) => {
      return new SuccessModel(res);
    });
  }
  if (method === "POST" && req.path === "/api/blog/del") {
    const logincheck = logincheck(req);
    if (logincheck) {
      return logincheck;
    }

    return deleteBlog(req.query.id, req.session.username).then((data) => {
      return new SuccessModel(data);
    });
  }
};
module.exports = handleBlogRouter;
